'''
Created on 2014-2-5

@author: apple
'''
from com.ad.sword.web.common import *
from com.ad.sword.dao.models import User, Role
import math

@tojson
@check_required_argument
def list(request):
    users = string_ifilter(request, User.objects, ["username", "email"])
    users = sort(request, users)
    page_no = int(request.REQUEST.get("page", 0))
    page_size = int(request.REQUEST.get("rows", 40))
    records=users.count()
    total=int(math.ceil(float(records)/page_size))
    list = {"items": [],  "page": page_no, "records": records,"total":total}
    users=users.skip(page_no * page_size).limit( page_size)
    for user in users:
        u={}
        for k in user:
            if k=='role' and user[k]:
                u['role_id']=str(user[k]['id'])
            elif k=='last_login_time':
                u[k]=time2str(user[k])
            else:
                u[k]=str(user[k])
        list['items'].append(u)

    return list

@tojson
@check_required_argument
def delete(request):
    ids = get_required_argument(request, "id").split(',')
    for id in ids:
        user=User.objects.get(id=id)
        user.delete()
    return message(_("OK"))



@tojson
@check_required_argument
def add(request):
    from django.db import IntegrityError

    user = User()
    user.username = get_required_argument(request, "username")
    user.password = get_required_argument(request, "password")
    user.email = get_required_argument(request, "email")
   
    user.description = request.REQUEST.get("description", '')
    role =Role.objects.get(id= get_required_argument(request, "role_id"))
    user.role =role
    try:
        user.save()
    except IntegrityError:
        try:
            User.objects.get(username=user.username)
        except DoesNotExist:
            return error_msg(msg = _("email %s already exist")% user.email)
        else:
            return error_msg(msg = _("username %s already exist")% user.username)
    request.log.Info(title=_("Add User"),description=_("Add user %s") % user.username);
    return message("OK")


@tojson
@check_login
@check_permission("Administrator")
def edit(request):
    from django.db import IntegrityError

    id = get_required_argument(request, "id")
    try:
        user = User.objects.get(id=id)
    except DoesNotExist:
        return error_msg(msg="Account does not exist")
    
    if request.REQUEST.get('username', None):
        user.username = request.REQUEST['username']

    if request.REQUEST.get('password', None):
        user.password = request.REQUEST['password']
    if request.REQUEST.get('email', None):
        user.email = request.REQUEST['email']
    if request.REQUEST.get('description', None):
        user.description = request.REQUEST["description"]

    if request.REQUEST.get('role_id', None):
        role_id = request.REQUEST["role_id"]
        user.role=Role.objects.get(id=role_id)

    try:
        user.save()
    except IntegrityError:
        return error_msg(msg = _("email %s already exist") % user.email)
    request.log.Info(title=_("Edit User"),description=_("Edit user %s") % user.username);
    return message(_("OK"))